package com.alks.function.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.config.handler.AutoCellWriteWidthHandle;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.common.utils.stringUtils.ZStringUtils;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.MpPurDisConditionDto;
import com.alks.function.data.dto.MpPurDisDto;
import com.alks.function.data.request.MpPurDisRequest2;
import com.alks.function.mapper.MpPurDisMapper;
import com.alks.function.service.MpPurDisService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
public class MpPurDisServiceImpl implements MpPurDisService {

    @Autowired
    private MpPurDisMapper mpPurDisMapper;

    /**
     * 材料订购明细
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getOrderDetails(MpPurDisRequest2 request) {
        Map map = new HashMap();
        request.setCompanyId(UserIdThread.get().getCompanyId());
        //查询材料订购明细
        List<MpPurDisDto> materialOrderDetails = mpPurDisMapper.getMaterialOrderDetails(request);
        for (MpPurDisDto materialOrderDetail : materialOrderDetails) {
            //订购数量
            float purQty = materialOrderDetail.getPurQty();
            //入库数量
            float qty = materialOrderDetail.getQty();

            //判断订购数量是否与入库数量相等
            if (purQty == qty) {
                materialOrderDetail.setBackgroundColor(1);
            } else if (purQty > qty) {
                materialOrderDetail.setBackgroundColor(2);
            } else {
                materialOrderDetail.setBackgroundColor(0);
            }
        }
        //统计订购数量
        float orderCount = mpPurDisMapper.getMaterialOrderCount(request);
        //统计金额
        BigDecimal AMTCount = mpPurDisMapper.getMaterialAMTCount(request);
        PageInfo list = new PageInfo(materialOrderDetails);
        map.put("materialOrderDetails", materialOrderDetails);
        map.put("total", list.getTotal());
        map.put("purQtyCount", orderCount);
        map.put("amtCount", AMTCount);
        return ResponseInfo.ok(map);
    }

    /**
     * 查询条件返回
     * @return
     */
    @Override
    public ResponseInfo getOrderCondition() {
        Map map=new HashMap();
        List<String> materialType = new ArrayList<>(Arrays.asList("面材","包材"));
        List<String> orderType = new ArrayList<>(Arrays.asList("汇总","零星","补单","正单","通样","样品单"));
        String companyId = UserIdThread.get().getCompanyId();
        List<String> sysUser = mpPurDisMapper.getSysUser(companyId);
        List<MpPurDisConditionDto> vendorName = mpPurDisMapper.getVendorName(companyId);
        map.put("materialType",materialType);
        map.put("orderType",orderType);
        map.put("sysUser",sysUser);
        map.put("vendorName",vendorName);
        return ResponseInfo.ok(map);
    }

    /**
     * 按查询导出明细
     * @param request
     * @param response
     */
    @Override
    public void exportMpPurDis(MpPurDisRequest2 request, HttpServletResponse response) {
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        List<MpPurDisDto> list = mpPurDisMapper.getMaterialOrderDetails(request);
        if (ZStringUtils.isEmpty(list)) {
            throw new ServiceErrorException("查询数据为空!");
        }
        //统计订购数量
        float count = mpPurDisMapper.getMaterialOrderCount(request);
        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        String fileName = "材料订购明细" + DateUtils.dateTimeNow() + ".xls";
        try (
                InputStream inputStream = new ClassPathResource("templates/材料订购明细模板.xls").getInputStream();
                OutputStream outputStream = response.getOutputStream();
                ExcelWriter excelWriter = EasyExcel.write(outputStream).excelType(ExcelTypeEnum.XLS).withTemplate(inputStream).registerWriteHandler(new AutoCellWriteWidthHandle()).build();
        ) {
            ExcelUtils.setResponseZF(response, fileName);
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(map, fillConfig, writeSheet);
            excelWriter.fill(new FillWrapper("t", list), fillConfig, writeSheet);
            excelWriter.finish();
        } catch (Exception e) {
            log.error("材料订购明细导出失败, 错误信息: {}", e.getMessage(), e);
            throw new ServiceErrorException("材料订购明细导出失败!");
        }
    }
}
